package com.yicong.ants.scenic.dialog

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.view.Gravity
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup.LayoutParams
import android.view.WindowManager
import android.widget.TextView
import com.blankj.utilcode.util.ToastUtils
import com.yicong.ants.R
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt

class SelectItemDialog(
    c: Context,
    currentLatitude: String?,
    currentLongitude: String?,
    longitude: String?,
    latitude: String?,
    n: String?
) : OnClickListener {

    constructor(c: Context, longitude: String?, latitude: String?, n: String?) : this(
        c = c,
        currentLatitude = "",
        currentLongitude = "",
        longitude = longitude,
        latitude = latitude,
        n = n
    ) {
        haveCurrent = false
    }

    //是否有起点
    private var haveCurrent = true
    private val context = c
    private val currentLa = currentLatitude ?: "0"
    private val currentLo = currentLongitude ?: "0"
    private val lo = longitude ?: "0"
    private val la = latitude ?: "0"
    private val name = n ?: ""
    private var dialog: Dialog = Dialog(context)

    init {
        dialog.setContentView(R.layout.dialog_select_item)

        dialog.findViewById<TextView>(R.id.item1)?.setOnClickListener(this)
        dialog.findViewById<TextView>(R.id.item2)?.setOnClickListener(this)
        dialog.findViewById<TextView>(R.id.cancel)?.setOnClickListener(this)

        val params = if (dialog.window?.attributes == null) {
            WindowManager.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
        } else {
            dialog.window?.attributes
        }
        params!!.width = LayoutParams.MATCH_PARENT

        dialog.window?.attributes = params
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.window?.setGravity(Gravity.BOTTOM)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.cancel -> {
                dialog.dismiss()
            }

            R.id.item1 -> {
                openGaoDeNavi(context)
            }

            R.id.item2 -> {
                openBaiduNavi(context)
            }
        }
    }

    fun show() {
        if (!isShowing()) {
            dialog.show()
        }
    }

    fun isShowing(): Boolean {
        return dialog.isShowing
    }

    fun dismiss() {
        dialog.dismiss()
    }

    private fun isAppInstalled(c: Context, appPackageName: String): Boolean {
        try {
            val pm = c.packageManager
            val info = pm.getPackageInfo(appPackageName, 0)
        } catch (e: Exception) {
            return false
        }
        return true
    }

    private fun openGaoDeNavi(context: Context) {
        val name = "com.autonavi.minimap"
        if (isAppInstalled(context, name)) {
            val stringBuffer = StringBuffer("amapuri://route/plan?")
            if (haveCurrent) {
                stringBuffer
                    .append("slat=")
                    .append(currentLa)
                    .append("&slon")
                    .append(currentLo)
                    .append("&")
            }
            stringBuffer
                .append("dlat=").append(la)
                .append("&dlon=").append(lo)
                .append("&dname=").append(this.name)
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()))
            intent.addCategory(Intent.CATEGORY_DEFAULT)
            intent.setPackage(name)
            context.startActivity(intent)
            dialog.dismiss()
        } else {
            ToastUtils.showLong("请安装高德地图后使用")
        }
    }

    private fun openBaiduNavi(context: Context) {
        val name = "com.baidu.BaiduMap"
        if (isAppInstalled(context, name)) {
            val stringBuffer = StringBuffer("baidumap://map/direction?mode=driving")
            if (haveCurrent) {
                stringBuffer
                    .append("&origin=latlng:")
                    .append(currentLa)
                    .append(",")
                    .append(currentLo)
            }
            val bdData = toBaiduMap(lo.toDouble(), la.toDouble())
            stringBuffer
                .append("&destination=latlng:")
                .append(bdData.bdLat)
                .append(",")
                .append(bdData.bdLng)
                .append("|name:")
                .append(this.name)
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(stringBuffer.toString()))
            intent.setPackage(name)
            context.startActivity(intent)
            dialog.dismiss()
        } else {
            ToastUtils.showLong("请安装百度地图后使用")
        }
    }

    fun toBaiduMap(lng: Double, lat: Double): BdData {
        val X_PI = Math.PI * 3000.0 / 180.0;
        val z = sqrt(lng * lng + lat * lat) + 0.00002 * sin(lat * X_PI)
        val theta = atan2(lat, lng) + 0.000003 * cos(lng * X_PI)
        val bdLng = z * cos(theta) + 0.0065
        val bdLat = z * sin(theta) + 0.006
        return BdData(bdLng.toString(), bdLat.toString())
    }

    data class BdData(var bdLng: String, var bdLat: String)
}